<template>
  <view class="bg">
    <!--设置-->
    <u-skeleton
        :rows="4"
        :loading="loadingStatus"
    >
      <view class="setting common">
        <u-cell-group
            title="消息通知"
        >
          <!--微信订阅消息-->
          <u-cell
              title="微信订阅通知"
              label="是否开启订阅消息通知">
            <view
                slot="value"
            >
              <u-switch
                  v-model="userInfo.notifyMp"
                  async-change
                  :loading="!btnStatus"
                  @change="mpSwitchChange"
              ></u-switch>
            </view>
          </u-cell>
          <!--邮件通知-->
          <u-cell
              title="邮件通知"
              label="是否开启邮件通知">
            <view
                slot="value"
            >
              <u-switch
                  v-model="userInfo.notifyEmail"
                  async-change
                  :loading="!btnStatus"
                  @change="emailSwitchChange"
              ></u-switch>
            </view>
          </u-cell>
          <!--短信通知-->
          <u-cell
              title="短信通知"
              label="是否开启短信通知">
            <view
                slot="value"
            >
              <u-switch
                  v-model="userInfo.notifySms"
                  async-change
                  :loading="!btnStatus"
                  @change="smsSwitchChange"
              ></u-switch>
            </view>
          </u-cell>
        </u-cell-group>
      </view>
      <!--退出登录-->
      <view class="btn">
        <u-button
            text="退出登录"
            type="error"
            shape="circle"
            plain
            @click="unLogin"
            :custom-style="{
            width:'50vw'
          }"
        ></u-button>
      </view>
    </u-skeleton>
    <u-toast ref="uToast"></u-toast>
    <u-modal
        :show="modal.status"
        :async-close="true"
        @confirm="modalConfirm"
        @cancel="modal.status=false"
        :title="modal.title"
        :content="modal.content"
        :show-cancel-button="true"
    ></u-modal>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {},
      btnStatus: true,
      loadingStatus: true,
      modal:{
        status: false,
        type:''
      }
    }
  },
  methods: {
    // 读取本地用户信息
    async getUserInfo() {
      let _this = this
      this.loadingStatus = true
      try {
        let userInfo = uni.getStorageSync("userInfo")
        let db = uniCloud.database()
        let res = (await db.collection('user').doc(userInfo._id).get()).result.data
        if (res.length > 0) {
          this.userInfo = res[0]
        } else {
        }
      } catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message: String(e) || '获取用户信息失败',
          type: 'error',
          complete() {
            _this.unLogin()
          }
        })
      }finally {
        this.loadingStatus =false
      }
    },
    // 退出登录
    unLogin() {
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('openId')
      uni.redirectTo({
        url: '/pages/Index'
      })
    },
    async mpSwitchChange(value) {
      if(value){
        this.userInfo.notifyMp = value
        await uni.requestSubscribeMessage({
          tmplIds: ['sVW1LT6sDt33czuxqq4qq0tUslwhwYPUgVN5wjYeod4', 'g4RMcRLwZxfvdtUFuxmGVis46XZAaeualEv6-vRAQEs', 'SqlXSDlBiaYv4KDDtz3BNPfb0-X_mNYDt_sV1OzhiZg'],
          success(res){
            console.log(res)
          }
        })
        await this.updateUserInfo()
      }else {
        this.modal={
          status: true,
          title: '警告',
          content: '关闭小程序订阅通知，您可能会错过图书到期和逾期提醒！',
          type: 'mp'
        }
      }
    },
    async smsSwitchChange(value){
      if(value){
        this.userInfo.notifySms = value
        await this.updateUserInfo()
      }else {
        this.modal={
          status: true,
          title: '警告',
          content: '关闭短信通知，您可能会错过图书到期和逾期提醒！',
          type: 'sms'
        }
      }
    },
    async emailSwitchChange(value) {
      if(value){
        this.userInfo.notifyEmail = value
        await this.updateUserInfo()
      }else {
        this.modal={
          status: true,
          title: '警告',
          content: '关闭右键通知，您可能会错过图书到期和逾期提醒！',
          type: 'email'
        }
      }
    },
    async modalConfirm(){
      try {
        switch (this.modal.type){
          case 'sms':{
            this.userInfo.notifySms = false
          }break;
          case 'mp':{
            this.userInfo.notifyMp = false
          }break;
          case 'email':{
            this.userInfo.notifyEmail = false
          }break;
          default:break;
        }
        await this.updateUserInfo()
      }catch (e){
        console.log(e)
        this.$refs.uToast.show({
          message:String(e)||'修改失败！',
          type:'error'
        })
      }finally {
        this.modal.status=false
      }
    },
    // 更新用户设置
    async updateUserInfo(){
      this.btnStatus=false
      try {
        let db = uniCloud.database()
        await db.collection('user')
            .doc(this.userInfo._id)
            .update({
              notifySms: this.userInfo.notifySms,
              notifyEmail: this.userInfo.notifyEmail,
              notifyMp:this.userInfo.notifyMp
            })
      }catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message: String(e) || "更改设置失败",
          type:'error'
        })
      }finally {
        this.btnStatus=true
      }
    }
  },
  onLoad(query) {
    this.getUserInfo()
  }
}
</script>

<style lang="scss">
.btn {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
}

</style>
